<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Validate;
use think\Config;
use think\Cache;

class Home extends Controller{
      //首页轮播图
      public function banner(){
         if(cache('banner')){
            $banner = cache('banner');
         }else{
             $banner = db('image')->field('img,type,url')->where("position = 1 AND state = 1")->select();
             foreach($banner as $key=>$value){
                 if(!Validate::is($value['img'],'url')){
                     $banner[$key]['img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value['img'];
                 }
             }
         }
         if($banner){
            cache('banner',$banner,30);
            return json_encode(['code'=>200,'msg'=>'请求成功','banner'=>$banner]);
         }else{
            return json_encode(['code'=>201,'msg'=>'暂无数据']);
         }
      }

      //新手指南
      public function beginnerGuide(){
        // if(cache('guide')){
        //     $guide = cache('guide');
        // }else{
            $guide = [['img'=>'/uploads/images/2018/beginnerguide.png']];
            foreach($guide as $key=>$value){
               $guide[$key]['img'] = 'https://'.$_SERVER['HTTP_HOST'].$value['img'];
            }
        //     cache('guide',$guide);
        // }
        // Cache::clear('guide');
        return json_encode(['code'=>200,'msg'=>'请求成功','guide'=>$guide]);
      }
      
      //首页文字广播
      public function broadcast(){
         if(cache('broadcast')){
            $broadcast = cache('broadcast');
         }else{
            $broadcast = db('broadcast')->field('user_id,content,type,create_time')
                                        ->where("state = 1")
                                        ->select();
            foreach($broadcast as $key=>$value){
                $broadcast[$key]['user_name'] = db('user')->where("user_id = {$value['user_id']}")->value('name');
                if((time() - $value['create_time']) < 60){
                    $broadcast[$key]['create_time'] = floor(time() - $value['create_time']).'秒前';
                }elseif((time() - $value['create_time']) > 60  && (time() - $value['create_time']) < 3600 ){
                    $broadcast[$key]['create_time'] = floor((time() - $value['create_time'])/60).'分钟前';
                }elseif((time() - $value['create_time']) > 3600 && (time() - $value['create_time']) < 86400){
                    $broadcast[$key]['create_time'] = floor((time() - $value['create_time'])/3600).'小时前';
                }elseif((time() - $value['create_time']) > 86400){
                    $broadcast[$key]['create_time'] = date('Y-m-d',$value['create_time']);
                }
            }
         }
         if($broadcast){
            cache('broadcast',$broadcast,30);
            return json_encode(['code'=>200,'msg'=>'请求成功','broadcast'=>$broadcast]);
         }else{
            return json_encode(['code'=>201,'msg'=>'暂无数据']);
         }
      }

      //首页导航 （各种小供功能模块上下架）
      public function navigation(){
            if(cache('navigation')){
                $navigation = cache('navigation');
            }else{
                $navigation = db('navigation')->field('name,url,img,type')
                                               ->where("state = 1")
                                               ->order(['sort desc,navigation'])
                                               ->select();
                foreach($navigation as $key=>$value){
                    if(!Validate::is($value['img'],'url')){
                          $navigation[$key]['img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value['img'];
                    }
                }
            }
            if($navigation){
                cache('navigation',$navigation,30);
                return json_encode(['code'=>200,'msg'=>'请求成功','navigation'=>$navigation]);
            }else{
                return json_encode(['code'=>201,'msg'=>'暂无数据']);
            }
      }

      //首页推荐分类
      public function recommend(){
         if(cache('label_info')){
            $label_info = cache('label_info');
         }else{
             $label_info = db('label')->field('label_id,name as first_level_label')->where("parent_id = 0 AND state = 1")->select();
             foreach($label_info as $key=>$value){
                $label_info[$key]['secondary_label'] = db('label')->field('label_id,name as secondary_label_name,image')->where("parent_id = {$label_info[$key]['label_id']}")->select();
                foreach($label_info[$key]['secondary_label'] as $k=>$v){
                    $label_info[$key]['secondary_label'][$k]['image'] = 'https://'.$_SERVER['HTTP_HOST'].$v['image'];
                }
             }
         }
         if($label_info){
            cache('label_info',$label_info,30);
            return json_encode(array('code'=>200,'msg'=>'请求成功','label_info'=>$label_info));
         }else{
            return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
         }
      }

      //首页中间 banner
      public function adviceBanner(){
         if(cache('advice_banner')){
            $banner = cache('advice_banner');
         }else{
             $banner = db('image')->field('img,type,url')->where("position = 2 AND state = 1")->select();
             foreach($banner as $key=>$value){
                 if(!Validate::is($value['img'],'url')){
                     $banner[$key]['img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value['img'];
                 }
             }
         }
         if($banner){
            cache('advice_banner',$banner,30);
            return json_encode(['code'=>200,'msg'=>'请求成功','banner'=>$banner]);
         }else{
            return json_encode(['code'=>201,'msg'=>'暂无数据']);
         }
      }

      //商品列表
      public function goodsList(){
         $page = input('post.page');
         if($page){
            if(!is_numeric($page)){
                return json_encode(array('code'=>401,'msg'=>'page参数类型有误'));
             }
         }else{
            $page = 0;
         }
         $map = 'shelves = 1';
         $type = input('post.type');
         if($type){
             $map .= " AND sale_type = {$type}";
         }else{
             $type = 0;
         }
         $cache_name = 'page'.$page.'_type'.$type;
         if(cache($cache_name)){
            $goodsList = cache($cache_name);
         }else{
            $goodsList = db('goods')->field('goods_id,name,mode,thumbnail_img,small,sale_type')
                                    ->where($map)
                                    ->order(['sale_type desc','sort desc','small desc'])
                                    ->limit($page*6,6)
                                    ->select();
            foreach($goodsList as $key=>$value){
                  $goodsList[$key]['price'] = $value['small'];
                  unset($goodsList[$key]['small']);
                  if(!Validate::is($value['thumbnail_img'],'url')){
                      $goodsList[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value['thumbnail_img'];
                  }
             }
         }
         if($goodsList){
            Cache::tag('goodsList')->set($cache_name,$goodsList,30);
            // Cache::clear('goodsList');
            return json_encode(array('code'=>200,'msg'=>'请求成功','goods_list'=>$goodsList));
         }else{
            return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
         }
      }

      //共享商品列表
      public function sharedGoodsList(){
          $page = input('post.page');
          $price = input('post.price');
          $browse_number = input('post.browse_number');
          if($page){
               if(!is_numeric($page)){
                    return json_encode(array('code'=>200,'msg'=>'page类型有误'));
                }
          }else{
            $page = 0;
          }
          $goods_cache_name = 'sale_type2_page'.$page.'_price'.$price.'_browser_number'.$browse_number;
          if(cache($goods_cache_name)){
               $goodsList = cache($goods_cache_name);
          }else{
               $where = "g.shelves = 1 AND sale_type = 2";
                if($price){
                    if($price == 1){
                        $order = 'goods_price asc';
                    }else{
                        $order = 'goods_price desc';
                    }
                }
                if($browse_number){
                    if($browse_number == 1){
                        $order = 'g.browse_number asc,goods_price desc';
                    }else{
                        $order = 'g.browse_number desc,goods_price desc';
                    }
                }
                if(!$price && !$browse_number){
                     $order = 'g.sort desc,goods_price desc';
                }
                $goodsList = db('goods')->alias('g')
                                        ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.small as goods_price')
                                        ->where($where)
                                        ->limit($page*6,6)
                                        ->order($order)
                                        ->select();
                foreach($goodsList as $k=>$v){
                    if($v['goods_id'] == '' || $v['goods_id'] == 'null' || $v['goods_id'] == 'undefined'){
                        unset($goodsList[$k]);
                    }
                    if(!Validate::is($v['thumbnail_img'],'url')){
                        $goodsList[$k]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['thumbnail_img'];
                    }
                }
         }
         if($goodsList){
            Cache::tag('sharedGoodsList')->set($goods_cache_name,$goodsList,30);
            return json_encode(array('code'=>200,'msg'=>'请求成功','goods_list'=>$goodsList));
         }else{
            return json_encode(['code'=>201,'msg'=>'暂无共享商品']);
         }
      }

     //商品详情
     public function goodsDetail(){
            $goods_id = input('post.goods_id');
            // $goods_id = 2;
            if(!is_numeric($goods_id)){
                return json_encode(array('code'=>401,'msg'=>'goods_id类型有误'));
            }
            $goods_type = input('post.goods_type');//1秒杀;2砍价;(goods_type字段用于区别秒杀、砍价)
            if($goods_type){
                if(!is_numeric($goods_type)){return json_encode(['code'=>401,'msg'=>'goods_type类型错误']);}
                if($goods_type != 1 && $goods_type != 2){return json_encode(['code'=>401,'msg'=>'goods_type取值错误']);}
                $spec_item = input('post.spec_item');//商品规格id
                if($goods_type == 1){
                    $seckill_id = input('post.seckill_id');
                    if(!is_numeric($seckill_id)){return json_encode(['code'=>401,'msg'=>'seckill_id类型错误']);}
                }elseif($goods_type == 2){
                    $bargain_id = input('post.bargain_id');
                    if(!is_numeric($bargain_id)){return json_encode(['code'=>401,'msg'=>'bargain_id类型错误']);}
                }
            }
            $where = "goods_id = {$goods_id}";
            db('goods')->where($where)->setInc('browse_number');
            if(cache('good'.$goods_id)){
               $goods_detail = cache('good'.$goods_id);
            }else{
               $goods_info = db('goods')->field('goods_id,name,mode,shelves,focus_img,details,detection,money,material,stone,food,inch,weight,stone_number,stone_type,stone_shape,cleanliness,color,stone_weight,main_stones,goods_stone_shape,auxiliary_stone_weight,number_of_auxiliary_stones,store_id,materiel_id,sale_type')
                                       ->where($where)
                                       ->find();
                $goods_detail = [];
                $goods_detail['goods_id'] = $goods_info['goods_id'];
                $goods_detail['goods_name'] = $goods_info['name'];
                $goods_detail['mode'] = $goods_info['mode'];//0一口价;1多规格;
                $goods_detail['shelves'] = $goods_info['shelves'];//0下架;1上架;
                $goods_detail['focus_img'] = explode(',',$goods_info['focus_img']);
                $goods_detail['sale_type'] = $goods_info['sale_type'];//1在售珠宝;2共享珠宝;
                $goods_detail['materiel_id'] = $goods_info['materiel_id'];//用于选择优惠券
                //商品焦点图
                foreach($goods_detail['focus_img'] as $key=>$value){
                    if(!Validate::is($value,'url')){
                        $goods_detail['focus_img'][$key] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value;
                    }
                }
                //商品详情图
                if(preg_match('/\<\/?p\>/',$goods_info['details'])){
                     $goods_detail['details'] = str_replace('/goods','https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').'/goods',$goods_info['details']);
                }
                $goods_detail['store_id'] = $goods_info['store_id'];
                $store_info = db('store')->field('name,img')->where("store_id = {$goods_info['store_id']}")->find();
                $goods_detail['store_name'] = $store_info['name'];
                $goods_detail['store_img'] = "https://".$_SERVER['HTTP_HOST'].$store_info['img'];
                //商品参数
                if($goods_info['detection']){$goods_detail['parameter'][0]['parameter_value'] = $goods_info['detection'];$goods_detail['parameter'][0]['parameter_name'] = '检查机构';}
                if($goods_info['money']){$goods_detail['parameter'][1]['parameter_value'] = $goods_info['money'];$goods_detail['parameter'][1]['parameter_name'] = '款号';}
                if($goods_info['material']){$goods_detail['parameter'][2]['parameter_value'] = $goods_info['material'];$goods_detail['parameter'][2]['parameter_name'] = '材质';}
                if($goods_info['stone']){$goods_detail['parameter'][3]['parameter_value'] = $goods_info['stone'];$goods_detail['parameter'][3]['parameter_name'] = '石料';}
                if($goods_info['food']){$goods_detail['parameter'][4]['parameter_value'] = $goods_info['food'];$goods_detail['parameter'][4]['parameter_name'] = '品名';}
                if($goods_info['inch']){$goods_detail['parameter'][5]['parameter_value'] = $goods_info['inch'];$goods_detail['parameter'][5]['parameter_name'] = '手寸';}
                if($goods_info['weight']){$goods_detail['parameter'][6]['parameter_value'] = $goods_info['weight'];$goods_detail['parameter'][6]['parameter_name'] = '净金重';}
                if($goods_info['stone_number']){$goods_detail['parameter'][7]['parameter_value'] = $goods_info['stone_number'];$goods_detail['parameter'][7]['parameter_name'] = '主石号';}
                if($goods_info['stone_type']){$goods_detail['parameter'][8]['parameter_value'] = $goods_info['stone_type'];$goods_detail['parameter'][8]['parameter_name'] = '主石类型';}
                if($goods_info['stone_shape']){$goods_detail['parameter'][9]['parameter_value'] = $goods_info['stone_shape'];$goods_detail['parameter'][9]['parameter_name'] = '主石形状';}
                if($goods_info['cleanliness']){$goods_detail['parameter'][10]['parameter_value'] = $goods_info['cleanliness'];$goods_detail['parameter'][10]['parameter_name'] = '净度';}
                if($goods_info['color']){$goods_detail['parameter'][11]['parameter_value'] = $goods_info['color'];$goods_detail['parameter'][11]['parameter_name'] = '颜色';}
                if($goods_info['stone_weight']){$goods_detail['parameter'][12]['parameter_value'] = $goods_info['stone_weight'];$goods_detail['parameter'][12]['parameter_name'] = '主石重';}
                if($goods_info['main_stones']){$goods_detail['parameter'][13]['parameter_value'] = $goods_info['main_stones'];$goods_detail['parameter'][13]['parameter_name'] = '主石数';}
                if($goods_info['goods_stone_shape']){$goods_detail['parameter'][14]['parameter_value'] = $goods_info['goods_stone_shape'];$goods_detail['parameter'][14]['parameter_name'] = '辅石形状';}
                if($goods_info['auxiliary_stone_weight']){$goods_detail['parameter'][15]['parameter_value'] = $goods_info['auxiliary_stone_weight'];$goods_detail['parameter'][15]['parameter_name'] = '辅石重';}
                if($goods_info['number_of_auxiliary_stones']){$goods_detail['parameter'][16]['parameter_value'] = $goods_info['number_of_auxiliary_stones'];$goods_detail['parameter'][16]['parameter_name'] = '辅石数';}
                //mode 0一口价;1多规格; sale_type 1在售珠宝;2共享珠宝;(以下价格显示在详情页,多规格对应价格、数量、押金、日租、商家日租金显示在spec规格数组里)
                if(!$goods_type){
                   if($goods_info['mode'] == 0){
                        $store_info = db('spec_goods_price')->field('price,store,market_price,deposit,rent,settlement')->where("goods_id = {$goods_info['goods_id']} AND price_key = 0")->find();
                        $goods_detail['goods_price'] = $store_info['price']; 
                        if($goods_info['sale_type'] == 2){
                           $goods_detail['market_price'] = $store_info['market_price'];
                           $goods_detail['goods_deposit'] = $store_info['deposit'];
                           $goods_detail['goods_rent'] = $store_info['rent'];
                           $goods_detail['goods_settlement'] = $store_info['settlement'];
                        }
                    }elseif($goods_info['mode'] == 1){
                        $map = "goods_id = {$goods_info['goods_id']} AND price_key > 0";
                        $min_price = db('spec_goods_price')->where($map)->min('price');
                        $map .= " AND price = {$min_price}";
                        $store_info = db('spec_goods_price')->field('price as goods_price,market_price,deposit,rent,settlement')->where($map)->find();
                        $goods_detail['goods_price'] = $store_info['goods_price'];
                        if($goods_info['sale_type'] == 2){
                           $goods_detail['market_price'] = $store_info['market_price'];
                           $goods_detail['goods_deposit'] = $store_info['deposit'];
                           $goods_detail['goods_rent'] = $store_info['rent'];
                           $goods_detail['goods_settlement'] = $store_info['settlement'];
                        }
                    }
                }else{
                    $str = "goods_id = {$goods_info['goods_id']} AND price_key = {$spec_item}";
                    $store_info = db('spec_goods_price')->field('price as goods_price,market_price,deposit,rent,settlement')->where($str)->find();
                    $goods_detail['goods_price'] = $store_info['goods_price'];
                    $goods_detail['market_price'] = $store_info['market_price'];
                    $goods_detail['goods_deposit'] = $store_info['deposit'];
                    $goods_detail['goods_rent'] = $store_info['rent'];
                    $goods_detail['goods_settlement'] = $store_info['settlement'];
                    //goods_type 1秒杀;2砍价;
                    if($goods_type == 1){
                        $seckill_info = db('goods_seckill')->field('price,end_time')->where("seckill_id = {$seckill_id}")->find();
                        $goods_detail['seckill_price'] = $seckill_info['price'];
                        $goods_detail['end_time'] = date("Y-m-d H:i:s",$seckill_info['end_time']);
                    }elseif($goods_type == 2){
                        $bargain_info = db('goods_bargain')->field('min_price,end_time')->where("bargain_id = {$bargain_id}")->find();
                        $goods_detail['bargain_price'] = $bargain_info['min_price'];
                        $goods_detail['end_time'] = date("Y-m-d H:i:s",$bargain_info['end_time']);
                    }
                }
            }
            $goods_spec = [];
            if(!$goods_type){
                $goods_mode_type = db('goods')->field('mode,sale_type')->where($where)->find();
                //商品对应价格、数量、押金、日租、商家日租金
                if($goods_mode_type['mode'] == 0){
                    $store_info = db('spec_goods_price')->field('store')->where("goods_id = {$goods_id} AND price_key = 0")->find();
                    $goods_spec['store'] = $store_info['store'];
                }elseif($goods_mode_type['mode'] == 1){
                    $map = "goods_id = {$goods_id} AND price_key > 0";
                    $goods_spec['store'] = db('spec_goods_price')->where($map)->sum('store');
                    $goods_spec['spec'] = db('spec_goods_price')->field('price_id,price_key,price_key_name,store,price,deposit,rent,settlement')
                                                                ->where($map)
                                                                ->select();
                    if($goods_mode_type['sale_type'] == 1){
                         foreach($goods_spec['spec'] as $s => $c){
                             unset($goods_spec['spec'][$s]['deposit']);
                             unset($goods_spec['spec'][$s]['rent']);
                             unset($goods_spec['spec'][$s]['settlement']);
                         }
                    }
                    foreach($goods_spec['spec'] as $k=>$v){
                        $goods_spec['spec'][$k]['price_key_name'] = db('spec_item')->where("item_id = {$v['price_key']}")->value('spec_item');
                    }
                }
                $postage = db('config')->where("name = 'postage'")->value('value');
            }else{
                $goods_spec['store'] = db('spec_goods_price')->where("goods_id = {$goods_id} AND price_key = {$spec_item}")->value('store');
            }
            // dump($goods_detail);die;
            if($goods_detail){
                Cache::set('good'.$goods_id,$goods_detail,30);
                if(!$goods_type){
                   return json_encode(array('code'=>200,'msg'=>'请求成功','goods_detail'=>$goods_detail,'goods_spec'=>$goods_spec,'postage'=>$postage));  
               }else{
                   return json_encode(array('code'=>200,'msg'=>'请求成功','goods_detail'=>$goods_detail,'goods_spec'=>$goods_spec)); 
               }
            }else{
                return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
            }
            
       }

       //判断商品有无被收藏
       public function isCollect(){
           $user_id = input('post.user_id');
           if(!is_numeric($user_id)){
              return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
           }
           $goods_id = input('post.goods_id');
           if(!is_numeric($goods_id)){
              return json_encode(['code'=>401,'msg'=>'goods_id类型错误']);
           }
           $map = "goods_id = {$goods_id} AND user_id = {$user_id}";
           $is_collect = db('goods_collection')->where($map)->value('collection_id');
           if($is_collect){
               return json_encode(['code'=>200,'msg'=>'该商品已被用户收藏']);
           }else{
               return json_encode(['code'=>201,'msg'=>'该商品未被用户收藏']);
           }
       }

       //商品收藏 
       public function myCollection(){
            $user_id = input('post.user_id');
            if(!is_numeric($user_id)){
                return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
            }
            $goods_id = input('post.goods_id');
            if(!is_numeric($goods_id)){
                return json_encode(['code'=>401,'msg'=>'goods_id类型错误']);
            }
            $type = input('post.type');//1收藏;2取消;
            if(!is_numeric($type)){
                return json_encode(['code'=>401,'msg'=>'type类型错误']);
            }
            if($type == 1){
               $data = array('goods_id' => $goods_id,'user_id' => $user_id,'create_time' => time());
               $collection = db('goods_collection')->insert($data); 
               if($collection){return json_encode(['code'=>200,'msg'=>'收藏成功']);}else{return json_encode(['code'=>201,'msg'=>'收藏失败']);}
            }elseif($type == 2){
               $map = "goods_id = {$goods_id} AND user_id = {$user_id}";
               $cancel_collection = db('goods_collection')->where($map)->delete();
               if($cancel_collection){return json_encode(['code'=>200,'msg'=>'取消收藏成功']);}else{return json_encode(['code'=>201,'msg'=>'取消收藏失败']);}
            }  
       }
       

       //到货提醒
       public function arrivalNotice(){
          $user_id = input('post.user_id');
          if(!is_numeric($user_id)){
             return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
          }
          $goods_id = input('post.goods_id');
          if(!is_numeric($goods_id)){
             return json_encode(['code'=>401,'msg'=>'goods_id类型错误']);
          }
          $type = input('post.type');
          if(!is_numeric($type)){
             return json_encode(['code'=>401,'msg'=>'缺少type参数']);
          }
          $noticeData = array('goods_id'=>$goods_id,'user_id'=>$user_id,'create_time'=>time());
          if($type == 1){
             $add_notice = db('shortage_goods')->insert($noticeData);
             if($add_notice){
                return json_encode(['code'=>200,'msg'=>'通知成功']);
             }else{
                return json_encode(['code'=>201,'msg'=>'通知失败']);
             }
          }elseif($type == 2){
              Db::startTrans();
              try{
                  $code = Cache::get('phone');
                  $phone = input('post.phone');
                  $verification_code = input('verification_code');
                  if($phone == 'undefined' || $phone == 'null' || $phone == ''){
                      return json_encode(array('code'=>401,'msg'=>'缺少手机号'));
                  }elseif($verification_code =='undefined' || $verification_code == 'null' || $verification_code == ''){
                      return json_encode(array('code'=>401,'msg'=>'缺少验证码'));
                  }
                  if(!$code){
                      return json_encode(array('code'=>401,'msg'=>'验证码过期'));
                  }
                  if($code != $verification_code){
                      return json_encode(array('code'=>401,'msg'=>'验证码错误','a'=>$code));
                  }
                  $data['phone'] = $phone;
                  $binding_phone = db('user')->where("user_id = {$user_id}")->update($data);
                  $add_notice = db('shortage_goods')->insert($noticeData);
                  Db::commit();
                  return json_encode(['code'=>200,'msg'=>'通知成功,手机号绑定成功']);
              }catch(\Exception $e){
                  Db::rollback();
                 return json_encode(['code'=>201,'msg'=>'通知失败,手机号绑定成功']);
              }
          }
       }

       //商品所属商店信息
       public function storeInfo(){
              $store_id = input('post.store_id');
              if(!is_numeric($store_id)){
                 return json_encode(array('code'=>401,'msg'=>'store_id类型错误'));
              }
              $cache_name = 'store'.$store_id;
              if(cache($cache_name)){
                 $store_info = cache($cache_name);
              }else{
                 $store_info = db('store')->field('store_id,name as store_name,img,address,lat,lng,tel')
                                          ->where("store_id = {$store_id}")
                                          ->find();
                if(!Validate::is($store_info['img'],'url')){
                        $store_info['img'] = 'https://'.$_SERVER['HTTP_HOST'].$store_info['img'];
                }
              }
              $page = input('post.page');
              $price = input('post.price');
              $browse_number = input('post.browse_number');
              if($page){
                   if(!is_numeric($page)){
                        return json_encode(array('code'=>200,'msg'=>'page类型有误'));
                    }
              }else{
                $page = 0;
              }
              $goods_cache_name = 'store_id'.$store_id.'_page'.$page.'_price'.$price.'_browser_number'.$browse_number;
              if(cache($goods_cache_name)){
                   $goodsList = cache($goods_cache_name);
              }else{
                   $where = "g.shelves = 1 AND store_id = {$store_id}";
                    if($price){
                        if($price == 1){
                            $order = 'goods_price asc';
                        }else{
                            $order = 'goods_price desc';
                        }
                    }
                    if($browse_number){
                        if($browse_number == 1){
                            $order = 'g.browse_number asc,g.goods_id';
                        }else{
                            $order = 'g.browse_number desc,g.goods_id';
                        }
                    }
                    if(!$price && !$browse_number){
                         $order = 'g.sort desc,g.goods_id';
                    }
                    $goodsList = db('goods')->alias('g')
                                            ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.small as goods_price')
                                            ->where($where)
                                            ->limit($page*6,6)
                                            ->order($order)
                                            ->select();
                    foreach($goodsList as $k=>$v){
                        if($v['goods_id'] == '' || $v['goods_id'] == 'null' || $v['goods_id'] == 'undefined'){
                            unset($goodsList[$k]);
                        }
                        if(!Validate::is($v['thumbnail_img'],'url')){
                            $goodsList[$k]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['thumbnail_img'];
                        }
                    }
             }
             if($store_info){
                 cache($cache_name,$store_info,30);
                 if($goodsList){
                    Cache::tag('storeGoodsList')->set($goods_cache_name,$goodsList,30);
                    return json_encode(array('code'=>200,'msg'=>'请求成功','store_info'=>$store_info,'goods_list'=>$goodsList));
                 }else{
                    return json_encode(['code'=>201,'msg'=>'该商店暂无商品信息','store_info'=>$store_info]);
                 }
             }else{
                 return json_encode(array('code'=>201,'msg'=>'暂无该商店信息'));
             }
       }


       //提交订单
       public function submitOrder(){
          $user_id = input('post.user_id');
          if(!is_numeric($user_id)){return json_encode(array('code'=>401,'msg'=>'user_id类型错误'));}
          $user_info = db('user')->field('openid,frozen_integral,available_integral')->where("user_id = {$user_id}")->find();
          $openid = $user_info['openid'];
          $store_id = input('post.store_id');
          if(!is_numeric($store_id)){return json_encode(array('code'=>401,'msg'=>'store_id类型错误'));}
          $order_type = input('post.order_type');//1快递;2自提
          if(!is_numeric($order_type)){return json_encode(array('code'=>401,'msg'=>'order_type类型错误'));}
          $type = input('post.type');//1在售;2共享;
          if(!is_numeric($type)){return json_encode(['code'=>401,'msg'=>'type类型错误']);}
          $data = array(
             'user_id' => $user_id,
             'store_id' => $store_id,
             'order_type' => $order_type
            );
          if($data['order_type'] == 1){
                 $name = input('post.name');
                 if($name == '' || $name == 'undefined' || $name == 'null'){return json_encode(array('code'=>401,'msg'=>'请选择有效的收货人姓名'));}
                 $data['name'] = $name;
                 $phone = input('post.phone');
                 if($phone =='' || $phone == 'undefined' || $phone == 'null'){return json_encode(array('code'=>401,'msg'=>'请填写有效的手机号'));}
                 $data['phone'] = $phone;
                 $consignee = input('post.consignee');
                 if($consignee == '' || $consignee == 'undefinde' || $consignee == 'null'){return json_encode(array('code'=>401,'msg'=>'请填写有效的收货人地址'));}
                 $data['consignee'] = $consignee;
                 if($type == 2){
                      $postage = input('post.postage');
                      if($postage != 0){
                         if($postage == '' || $postage == 'null' || $postage == 'undefined'){
                             return json_encode(['code'=>401,'msg'=>'缺少邮费参数']);
                         }
                         $real_postage = db('config')->where("name = 'postage'")->value('value');
                         if($postage != $real_postage){
                             return json_encode(['code'=>401,'msg'=>'postage参数被篡改']);
                         }
                      }
                      $data['postage'] = $postage;
                  }
          }
          $goods_price_sum = input('post.goods_price_sum');
          if($goods_price_sum == '' || $goods_price_sum == 'undefined' || $goods_price_sum == 'null'){
             return json_encode(array('code'=>401,'msg'=>'请填写订单金额'));
          }
          $data['goods_price'] = $goods_price_sum;//订单金额  用于后期优惠金额的计算;
          $pay_price = input('post.pay_price');
          if($pay_price == '' || $pay_price == 'undefined' || $pay_price == 'null'){
              return json_encode(['code'=>401,'msg'=>'实际支付金额缺失']);
          }
          $data['pay_price'] = $pay_price;//实际支付金额;在后期会添加优惠券等功能
          $use_id = input('post.use_id');
          $preferential_price = input('post.preferential_price');//优惠金额
          //$type1在售;2共享;
          if($type == 1){
              $data['order_sn'] = 'B'.generateOrderNum();
              $data['type'] = 2;
              if($use_id){
                  if(!is_numeric($use_id)){
                     return json_encode(['code'=>401,'msg'=>'use_id类型错误']);
                   }
                   $data['preferential_price'] = $preferential_price;
                   $data['use_id'] = $use_id;
                   $coupons_id = db('coupons_use')->where("use_id = {$use_id}")->value('coupons_id'); 
                   $coupons_info = db('coupons')->field('coupons_type,scope,conditions,discount,start_time,settlement_time')
                                                ->where("coupons_id = {$coupons_id}")
                                                ->find();
                   if($coupons_info['scope'] == 0){return json_encode(['code'=>401,'msg'=>'优惠券使用范围scope出错']);}
                   if($data['goods_price'] < $coupons_info['conditions']){return json_encode(['code'=>401,'msg'=>'该优惠券未满足使用条件']);}
                   if(time() < $coupons_info['start_time']){return json_encode(['code'=>401,'msg'=>'该优惠券还未生效']);}
                   if(time() > $coupons_info['settlement_time']){return json_encode(['code'=>401,'msg'=>'该优惠券已失效']);} 
                   if($coupons_info['coupons_type'] == 2){$coupons_info['discount'] = round($data['goods_price'] * (1 - $coupons_info['discount']/100),2);}
                   if($preferential_price != $coupons_info['discount']){return json_encode(['code'=>401,'msg'=>'优惠金额错误']);}
              }
          }elseif($type == 2){
              $data['order_sn'] = 'S'.generateOrderNum();
              $data['type'] = 1;
              $deposit_price = input('post.deposit_price');
              if($deposit_price != 0){
                 if($deposit_price == '' || $deposit_price == 'undefined' || $deposit_price == 'null'){
                     return json_encode(['code'=>401,'msg'=>'现付押金金额缺失']);
                  }
              }
              $data['deposit_price'] = $deposit_price;
              $integral = input('post.integral');
              if($integral != 0){
                     if($integral == '' || $integral == 'undefined' || $integral == 'null'){
                         return json_encode(['code'=>401,'msg'=>'抵押押金缺失']);
                     }
                     //抵押押金不能超过可用押金;
                     if($integral > $user_info['available_integral']){
                         return json_encode(['code'=>401,'msg'=>'可用押金被篡改']);
                     }
              }
          }
           $data['channel'] = input('post.channel');
           $data['store_user_sn'] = input('post.store_user_sn');
          $data['add_time'] = time();
          $mode = input('post.mode');
          $goods = json_decode(input('post.goods'),true);
          $goods_name = [];
          foreach($goods as $key=>$value){
                //求商品名
                $goods_list_name = db('goods')->where("goods_id = {$value['goods_id']}")->value('name');
                $goods_name[] = $goods_list_name.'*'.$value['goods_number'];
                $field = 'store,price,deposit,rent,settlement';
                if($mode == 1){
                    $goods_info = db('spec_goods_price')->field($field)->where("goods_id = {$value['goods_id']} AND price_key = {$value['spec_item']}")->find();
                }else{
                    $goods_info = db('spec_goods_price')->field($field)->where("goods_id = {$value['goods_id']} AND price_key = 0")->find();
                }
                $goods[$key]['goods_real_price'] = $goods_info['price'];
                $goods[$key]['goods_real_store'] = $goods_info['store'];
                if($data['type'] == 1){
                    $goods[$key]['goods_real_deposit'] = $goods_info['deposit'];
                    $goods[$key]['goods_real_rent'] = $goods_info['rent'];
                    $goods[$key]['goods_real_settlement'] = $goods_info['settlement'];
                }
          }
          $goods_name = implode(',',$goods_name);
          $price = [];
          $deposit = [];
          foreach($goods as $k=>$v){
                if($goods[$k]['goods_real_price'] != $goods[$k]['goods_price']){
                        return json_encode(array('code'=>401,'msg'=>'goods_price参数被篡改'));
                }
                unset($goods[$k]['goods_real_price']);
                if($goods[$k]['goods_number'] > $goods[$k]['goods_real_store']){
                    return json_encode(array('code'=>401,'msg'=>'库存不足,请重新进行选择'));
                }
                unset($goods[$k]['goods_real_store']);
                if($data['type'] == 1){
                    if($goods[$k]['goods_real_deposit'] != $goods[$k]['deposit']){
                        return json_encode(['code'=>401,'msg'=>'deposit参数被篡改']);
                    }
                    unset($goods[$k]['goods_real_deposit']);
                    if($goods[$k]['goods_real_rent'] != $goods[$k]['rent']){
                        return json_encode(['code'=>401,'msg'=>'rent参数被篡改']);
                    }
                    unset($goods[$k]['goods_real_rent']);
                    if($goods[$k]['goods_real_settlement'] != $goods[$k]['settlement']){
                        return json_encode(['code'=>401,'msg'=>'settlement参数被篡改']);
                    }
                    unset($goods[$k]['goods_real_settlement']);
                    $deposit[] = $goods[$k]['deposit']*$goods[$k]['goods_number'];
                }elseif($data['type'] == 2){
                    unset($goods[$k]['deposit']);
                    unset($goods[$k]['rent']);
                    unset($goods[$k]['settlement']);
                    $price[] = $goods[$k]['goods_price']*$goods[$k]['goods_number'];
                }
          }
          //$data['type']  1共享  2在线销售
          if($data['type'] == 2){
             $goods_name = '购买珠宝（'.$goods_name.'）'; 
             $price_sum = array_sum($price);
             $real_goods_price = $price_sum;  
             if($price_sum != $goods_price_sum){return json_encode(array('code'=>401,'msg'=>'订单总价不对'));}   
             $real_pay_price = ($real_goods_price - $preferential_price) > 0?round(($real_goods_price - $preferential_price),2):0;  //$real_pay_price 用于后期减去优惠券金额等  
          }elseif($data['type'] == 1){
             $goods_name = '共享珠宝（'.$goods_name.'）';
             $deposit_sum = array_sum($deposit);//商品押金总计
             // var_dump($deposit_sum);
             // var_dump($integral);
             if($integral){
                 if($integral > $deposit_sum){
                     return json_encode(['code'=>401,'msg'=>'抵押押金不能超过商品总押金']);
                 }
                 $deposit_sum = $deposit_sum - $integral ;//如果可用押金存在,则使用商品总押金减去可用押金;
                 $userInfoData = [];
                 $userInfoData['frozen_integral'] = $user_info['frozen_integral'] + $integral;//如果使用该可用押金,则需要冻结该部分押金;
                 $userInfoData['available_integral'] = $user_info['available_integral'] - $integral;//可用押金也需要减去相应押金;
             }
             $deposit_sum = round($deposit_sum,2);
             // var_dump($deposit_sum);
             if($deposit_sum != $deposit_price){return json_encode(['code'=>401,'msg'=>'现付押金金额不对']);}
             //$data['order_type'] 1为快递; 2 自提;
             if($data['order_type'] == 1){
                $real_goods_price = $deposit_sum + $data['postage'];
             }elseif($data['order_type'] == 2){
                $real_goods_price = $deposit_sum;
             }
             //$real_goods_price订单总价;
             if($real_goods_price != $goods_price_sum){return json_encode(['code'=>401,'msg'=>'订单总价不对']);}
             $real_pay_price = $real_goods_price;
          }  
          if($real_pay_price != $data['pay_price']){return json_encode(['code'=>401,'msg'=>'实际支付金额不对','c'=>$real_pay_price]);}
             //$data['type'] 为1表示共享珠宝;$data['type']为2表示在线销售;  
             Db::startTrans();
             try{ 
                    //共享珠宝订单  快递方式,邮费为0或上门自提方式,现付押金与小白信用押金抵消即支付金额为0时也可支付;
                    // if($data['type'] == 1 && $data['pay_price'] == 0){
                    //     $data['order_status'] = 1;
                    //     $data['pay_time'] = time();
                    // }
                    if($data['pay_price'] == 0){
                        $data['order_status'] = 1;
                        $data['pay_time'] = time();
                    }
                    if($use_id){db('coupons_use')->where("use_id = {$use_id}")->update(['state'=>1]);}
                    //共享订单  使用抵押押金后,用户对应的冻结押金及可用押金均需发生相应变化;
                    if($data['type'] == 1){
                        if($integral){
                            db('user')->where("user_id = {$user_id}")->update($userInfoData);
                        }
                    }


                    $order_id = db('order')->insertGetId($data);
                    foreach($goods as $k=>$vo){
                        $goods[$k]['order_id'] = $order_id;
                    }
                    $add_goods = db('order_goods')->insertAll($goods);
                    $goods_info = db('order_goods')->field('order_goods_id,goods_id,spec_item,goods_number,settlement')->where("order_id = {$order_id}")->select();$settlement_price = 0;
                    foreach($goods_info as $k=>$vo){
                        $where = "goods_id = {$vo['goods_id']} AND price_key = {$vo['spec_item']}";
                        db('spec_goods_price')->where($where)->setDec('store',$vo['goods_number']);
                        $price_id = db('spec_goods_price')->where($where)->value('price_id');
                        $code = [];
                        for($i=0;$i<$vo['goods_number'];$i++){
                            $code_id = db('code')->field('code_id')->where("price_id = {$price_id} AND state = 0")->order('code_id')->find();
                            $update_data = array('state'=>1,'update_time'=>time(),'sale_type'=>1);
                            db('code')->where("code_id = {$code_id['code_id']}")->update($update_data);
                            $code[] = $code_id['code_id'];
                        }
                        $code = implode(',',$code);
                        db('order_goods')->where("order_goods_id = {$vo['order_goods_id']}")->update(['code'=>$code]);
                        //商家结算
                        if($data['type']==2){
                                $goods_price['goods_id'] = $vo['goods_id'];
                                $goods_price['price_key'] = $vo['spec_item'];
                                $settlement_price += db('spec_goods_price')->where($goods_price)->value('settlement_price');

                        }elseif ($data['type']==1){
                                $settlement_price += $vo['goods_number']*$vo['settlement'];
                        }

                    }
                 db('order')->where("order_id = {$order_id}")->update(['business_settlement_price'=>$settlement_price]);
                    $logData = [];
                    $logData['order_id'] = $order_id;
                    $logData['u_id'] = $user_id;
                    $logData['content'] = '用户下单';
                    $logData['create_time'] = time();
                    db('order_log')->insert($logData);

                    if($data['pay_price'] > 0){
                        // 实例支付接口
                        $pay = & load_wechat('Pay');
                        // 获取预支付ID
                        $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/api/Home/notify';
                        //$data['pay_price'] = 0.01;
                        $prepayid = $pay->getPrepayId($openid,$goods_name, $data['order_sn'], $data['pay_price'] * 100, $notify_url, $trade_type = "JSAPI");
                        // dump($prepayid);die;

                        // 创建JSAPI签名参数包
                        $options = $pay->createMchPay($prepayid);
                    }
                    Db::commit();
             } catch (\Exception $e){
                    Db::rollback();
                    return json_encode(['code' => 201,'msg' => '订单提交失败']);
             }
             // if($data['type'] == 1 && $data['pay_price'] == 0){ 
             //      return json_encode(['code'=>200,'msg'=>'提交成功','order_id' => $order_id]);
             // }
             // if($data['type'] == 2 && $data['pay_price'] == 0){
             //      return json_encode(['code'=>200,'msg'=>'提交成功','order_id'=>$order_id]);
             // }
             if($data['pay_price'] == 0){
                  return json_encode(['code'=>200,'msg'=>'提交成功','order_id'=>$order_id]); 
             }
             if($data['pay_price'] > 0){
                  return json_encode(['code' => 200,'msg' => '提交成功','pay' => $options,'order_id' => $order_id]);
             }
       }

       //回调
       public function notify(){
            // 实例支付接口
            $pay = & load_wechat('Pay');

            // 获取支付通知
            $notifyInfo = $pay->getNotify();

            // 支付通知数据获取失败
            if($notifyInfo===FALSE){
                // 接口失败的处理
                echo $pay->errMsg;
            }else{
                //支付通知数据获取成功
                 if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                    $order = db('order')->where("order_sn = '{$notifyInfo['out_trade_no']}'")->find();
                    if($order['order_status'] > 0){
                        return FALSE;
                    }
                    if($order['type']==2){
                    //查询用户有没有分销关系
                    $user_info = db('user')->field('leader,upper_level_id')->where("user_id = {$order['user_id']}")->find();
                    if($user_info['leader']){
                         //查询商品的分销佣金
                        $goods_info = db('order_goods')->field('goods_id,goods_number,goods_price')->where("order_id = {$order['order_id']}")->select();
                        $one_commission = [];
                        $two_commission = [];
                        foreach($goods_info as $key=>$value){
                            $materiel_id = db('goods')->where("goods_id = {$value['goods_id']}")->value('materiel_id');
                            $commission_proportion = db('materiel')->field('one_proportion,two_proportion')->where("materiel_id = {$materiel_id}")->find();
                            $one_commission[] = ($order['goods_price']-$order['preferential_price'])*$commission_proportion['one_proportion']/100;
                            $two_commission[] = ($order['goods_price']-$order['preferential_price'])*$commission_proportion['two_proportion']/100;
                        }
                        $one_commission_sum = array_sum($one_commission);
                        $two_commission_sum = array_sum($two_commission);
                        $ordercommission = $one_commission_sum+$two_commission_sum;
                        $commissionsData = [];
                        $commissionsData['user_id'] = $user_info['leader'];
                        $commissionsData['suser_id'] = $order['user_id'];
                        $commissionsData['add_time'] = time();
                        $commissionsData['order_id'] = $order['order_id'];
                        $commissionsData['commission'] = $one_commission_sum;
                        if($user_info['upper_level_id']){
                            $commissionsData['upper_level_id'] = $user_info['upper_level_id'];
                            $commissionsData['upper_level_commission'] = $two_commission_sum;
                        }
                    }
                    }
                    Db::startTrans();
                    try{
                        //本订单佣金计算
                        if($order['type']==2){
                            if($user_info['leader']){
                                 db('commissions')->insert($commissionsData);
                                 db('user')->where("user_id = {$user_info['leader']}")->setInc('unsettled_money',$one_commission_sum);
                                 if($user_info['upper_level_id']){
                                     db('user')->where("user_id = {$user_info['upper_level_id']}")->setInc('unsettled_money',$two_commission_sum);
                                 }
                            }

                            $goods_info = db('order_goods')->field('goods_id,spec_item')->where("order_id = {$order['order_id']}")->select();
                            $settlement_price = 0;
                            foreach ($goods_info as $k=>$it){
                                $goods_price['goods_id'] = $it['goods_id'];
                                $goods_price['price_key'] = $it['spec_item'];
                                $settlement_price += db('spec_goods_price')->where($goods_price)->value('settlement_price');
                            }
                        }elseif ($order['type']==1){
                            $goods_info = db('order_goods')->field('goods_id,settlement,goods_number')->where("order_id = {$order['order_id']}")->select();
                            $settlement_price = 0;
                            foreach ($goods_info as $k=>$it){
                                $settlement_price += $it['goods_number']*$it['settlement'];
                            }
                        }
                        $data = [];
                        $data['order_status'] = 1;
                        $data['pay_time'] = time();
                        if(!isset($one_commission_sum)){
                            $ordercommission = 0;
                        }
                        $data['commission'] = $ordercommission;
                        $data['business_settlement_price'] = $settlement_price;
                        db('order') -> where("order_sn = '{$notifyInfo['out_trade_no']}'") -> update($data);
                        $addData = [];
                        $addData['order_id'] = $order['order_id'];
                        if($order['type'] == 1){$addData['type'] = 1;}
                        $addData['pay_code'] = $notifyInfo['transaction_id'];
                        $addData['pay_price'] = $notifyInfo['total_fee']/100;
                        $addData['time'] = strtotime($notifyInfo['time_end']);
                        $addData['notify_info'] = json_encode($notifyInfo);
                        db('order_pay')->insert($addData);
                        $logData = [];
                        $logData['order_id'] = $order['order_id'];
                        $logData['u_id'] = $order['user_id'];
                        $logData['content'] = '用户支付。支付方式:微信支付;交易流水号:'.$notifyInfo['transaction_id'].';交易金额:￥'.$addData['pay_price'].'。';
                        $logData['create_time'] = time();
                        db('order_log')->insert($logData);
                        Db::commit();
                     } catch (\Exception $e) {
                        Db::rollback();
                     }
                     $pay->replyXml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
                 }
            }
       }

       //分类
       public function classification(){
           if(cache('classify')){
               $new_array = cache('classify');
           }else{
               $classify_array = db('label')->field('label_id,name,parent_id,image')->select();
               $new_array = $this->generateTree($classify_array);
               foreach($new_array as $key=>$value){
                 unset($new_array[$key]['parent_id']);
                 unset($new_array[$key]['image']);
                 foreach($new_array[$key]['son'] as $k=>$v){
                    unset($new_array[$key]['son'][$k]['parent_id']);
                    $new_array[$key]['son'][$k]['image'] = 'https://'.$_SERVER['HTTP_HOST'].$v['image'];
                 }
               }
           }
           if($new_array){
              cache('classify',$new_array,30);
              return json_encode(array('code'=>200,'msg'=>'请求成功','classify'=>$new_array));
           }else{
              return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
           }
       }

       //筛选
       public function filter(){
          $filter_array = db('label')->field('label_id,name,parent_id')->select();
          $new_array = $this->generateTree($filter_array);
          foreach($new_array as $key=>$value){
             unset($new_array[$key]['parent_id']);
             foreach($new_array[$key]['son'] as $k=>$v){
                unset($new_array[$key]['son'][$k]['parent_id']);
             }
           }
           if($new_array){
              return json_encode(array('code'=>200,'msg'=>'请求成功','filter'=>$new_array));
           }else{
              return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
           }
       }


       public function generateTree($array){
            //第一步 构造数据
            $items = array();
            foreach($array as $value){
                $items[$value['label_id']] = $value;
            }
            //第二部 遍历数据 生成树状结构
            $tree = array();
            foreach($items as $key => $value){
                if(isset($items[$value['parent_id']])){
                    $items[$value['parent_id']]['son'][] = &$items[$key];
                }else{
                    $tree[] = &$items[$key];
                }
            }
            return $tree;
        }
       

        /**
         * 递归实现无限极分类
         * @param $array 分类数据
         * @param $pid 父ID
         * @param $level 分类级别
         * @return $list 分好类的数组 直接遍历即可 $level可以用来遍历缩进
         */

        public function getTree($array, $pid =0, $level = 0){

            //声明静态数组,避免递归调用时,多次声明导致数组覆盖
            static $list = [];
            foreach ($array as $key => $value){
                //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
                if ($value['parent_id'] == $pid){
                    //父节点为根节点的节点,级别为0，也就是第一级
                    $value['level'] = $level;
                    //把数组放到list中
                    $list[] = $value;
                    //把这个节点从数组中移除,减少后续递归消耗
                    unset($array[$key]);
                    //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                    $this->getTree($array, $value['label_id'], $level+1);

                }
            }
            return $list;
        }

        //分类详情页
        public function classifiedProduct(){
            $page = input('post.page');
            $label_id = input('post.label_id');
            $price = input('post.price');
            $browse_number = input('post.browse_number');
            if($page){
               if(!is_numeric($page)){
                    return json_encode(array('code'=>401,'msg'=>'参数page类型有误'));
                }
            }else{
                $page = 0;
            }
            if($label_id == '' || $label_id == 'null' || $label_id == 'undefined'){
                return json_encode(array('code'=>401,'msg'=>'参数label_id缺失'));
            }
            $map = "g.shelves = 1";
            $sale_type = input('post.sale_type');//2共享;
            if($sale_type){
               if(!is_numeric($sale_type)){
                   return json_encode(['code'=>401,'msg'=>'sale_type类型错误']);
               }
               $map .= " AND g.sale_type = 2";
               $cache_name = 'sale_type'.$sale_type.'_page'.$page.'_label_id'.$label_id.'_price'.$price.'_browse_number'.$browse_number;
            }else{
               $cache_name = 'page'.$page.'_label_id'.$label_id.'_price'.$price.'_browse_number'.$browse_number;
            }
            $store_id = input('post.store_id');
            if($store_id){
                if(!is_numeric($store_id)){
                    return json_encode(['code'=>401,'msg'=>'store_id类型错误']);
                }
                $map .= " AND g.store_id = {$store_id}";
                $cache_name = 'store_id'.$store_id.'_page'.$page.'_label_id'.$label_id.'_price'.$price.'_browse_number'.$browse_number;
            }else{
                $cache_name = 'page'.$page.'_label_id'.$label_id.'_price'.$price.'_browse_number'.$browse_number;
            }
            if(cache($cache_name)){
                $goodsList = cache($cache_name);
            }else{
                if($browse_number){
                    if($browse_number == 1){
                        $order = 'g.browse_number asc,goods_price desc';
                    }else{
                        $order = 'g.browse_number desc,goods_price desc';
                    }
                }
                if($price){
                    if($price == 1){
                       $order = 'goods_price';
                    }else{
                       $order = 'goods_price desc';
                    }
                }
                if(!$browse_number && !$price){
                    $order = 'g.sort,goods_price desc';
                }
                
                if($label_id){
                   if(is_numeric($label_id)){
                      $goodsList = db('goods_label')->alias('l')
                                                    ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.small as goods_price')
                                                    ->join('goods g','g.goods_id = l.goods_id','RIGHT')
                                                    ->where('FIND_IN_SET(:label_id,l.label_id)',['label_id'=>$label_id])
                                                    ->where($map)
                                                    ->order($order)
                                                    ->limit($page*6,6)
                                                    ->select();
                   }elseif(is_string($label_id)){
                      $label_id = explode(',',$label_id);
                      $where = [];
                      foreach($label_id as $k=>$vo){
                         $where[] = "(l.label_id LIKE '{$vo},%' OR l.label_id LIKE '%,{$vo},%' OR l.label_id LIKE '%,{$vo}')";
                      }
                      $where = implode(' AND ',$where);
                      $goodsList = db('goods_label')->alias('l')
                                                    ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.small as goods_price')
                                                    ->join('goods g','g.goods_id = l.goods_id','RIGHT')
                                                    ->where($where)
                                                    ->where($map)
                                                    ->order($order)
                                                    ->limit($page*6,6)
                                                    ->select();
                   }
                }
                foreach($goodsList as $key=>$v){
                    if(!Validate::is($v['thumbnail_img'],'url')){
                        $goodsList[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['thumbnail_img'];
                    }
                }
            }
            if($goodsList){
                Cache::tag('labelGoodsList')->set($cache_name,$goodsList,30);
                return json_encode(array('code'=>200,'msg'=>'请求成功','goods_list'=>$goodsList));
            }else{
                return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
            }
        }

        //搜索
        public function search(){
            $page = input('post.page');
            $keyword = input('post.keyword');
            $price = input('post.price');
            $browse_number = input('post.browse_number');
            if($page){
               if(!is_numeric($page)){
                    return json_encode(array('code'=>200,'msg'=>'page类型有误'));
                }
            }else{
                $page = 0;
            }
            if(empty($keyword)){
                return json_encode(array('code'=>201,'msg'=>'请输入关键词'));
            }
            $cache_name = 'page'.$page.'_keyword'.$keyword.'_price'.$price.'_browser_number'.$browse_number;
            if(cache($cache_name)){
                $goodsList = cache($cache_name);
            }else{
                $where = 'g.shelves = 1';
                if($keyword){
                    $where .= " AND g.name LIKE '%{$keyword}%'";
                }
                if($price){
                    if($price == 1){
                        $order = 'goods_price asc';
                    }else{
                        $order = 'goods_price desc';
                    }
                }
                if($browse_number){
                    if($browse_number == 1){
                        $order = 'g.browse_number asc,goods_price desc';
                    }else{
                        $order = 'g.browse_number desc,goods_price desc';
                    }
                }
                if(!$price && !$browse_number){
                     $order = 'g.sort desc,goods_price desc';
                }
                $goodsList = db('goods')->alias('g')
                                        ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.small as goods_price')
                                        ->where($where)
                                        ->limit($page*6,6)
                                        ->order($order)
                                        ->select();
                foreach($goodsList as $k=>$v){
                    if($v['goods_id'] == '' || $v['goods_id'] == 'null' || $v['goods_id'] == 'undefined'){
                        unset($goodsList[$k]);
                    }
                    if(!Validate::is($v['thumbnail_img'],'url')){
                        $goodsList[$k]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['thumbnail_img'];
                    }
                }
            }
            if($goodsList){
                Cache::tag('searchGoodsList')->set($cache_name,$goodsList,30);
                return json_encode(array('code'=>200,'msg'=>'请求成功','goods_list'=>$goodsList));
            }else{
                return json_encode(array('code'=>201,'msg'=>'请求失败或数据为空'));
            }
        }
}